package com.aim.common.util;

import javax.servlet.http.HttpServletRequest;

/**
 * @AUTO 防SQL注入工具类
 * @Author AIM
 * @DATE 2019/5/22
 */
public class AntiSQLInjectionUtil {

    public final static String regex = "'|%|--|and|or|not|use|insert|delete|update|select|count|group|union" +
            "|create|drop|truncate|alter|grant|execute|exec|xp_cmdshell|call|declare|source|sql";

    /**
     * @param param
     * @return 把SQL关键字替换为空字符串
     */
    public static String filter(String param) {
        if (param == null) {
            return param;
        }
        return param.replaceAll("(?i)" + regex, ""); // (?i)不区分大小写替换
    }

    /**
     * @param request 请求对象
     * @param name    参数名
     * @return 返回经过防注入处理的字符串
     */
    public static String getParameter(HttpServletRequest request, String name) {
        return AntiSQLInjectionUtil.filter(request.getParameter(name));
    }
}
